package com.yudean.esb.controller;


import com.yudean.esb.common.ServiceConstant;
import com.yudean.esb.security.SysAppUserService;
import com.yudean.esb.service.MdsLnfinDataService;
import com.yudean.esb.service.MdsLnplnDataService;
import com.yudean.esb.util.PageUtil;
import com.yudean.esb.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 蓝科财务报表数据
 * 蓝科 ——> 中间库 ——> 外围系统
 * @author szq
 * @since 2021-09-24
 */
@RestController
@RequestMapping("/lnapp")
@Slf4j
public class MdsLnAppDataController {
    @Resource
    private MdsLnfinDataService mdsLnfinDataService;
    @Resource
    private MdsLnplnDataService mdsLnplnDataService;
    @Resource
    private SysAppUserService sysAppUserService;

    static String perCompCode = "";
    static String perUserName = "";
    static String perPasswd = "";

    @GetMapping("/get/{serviceID}")
    public String getLnAppData(@PathVariable String serviceID, String compCode, String period,@RequestParam(required = false)String formId,
                               @RequestParam(required = false)String formName,@RequestParam(required = false)String accountId,
                               @RequestParam(required = false)String accountName,@RequestParam(required = false,defaultValue = "1")String pageNo,
                               @RequestParam(required = false)String valueType,@RequestParam(required = false,defaultValue = "5000") String pageSize,
                               String userName, String password) {
        log.info("getLnAppData():request-{serviceID:{},compCode:{},period:{},formName:{},accountName:{},pageNo:{},pageSize:{},userName:{}}",
                                                                        serviceID, compCode, period, formName, accountName, pageNo, pageSize, userName);
        try{
            String SERVICEIDS = "LNFIN,LNPLN";
            //判断ServiceID是否正确
            if (StringUtil.isEmpty(serviceID.trim()) || !SERVICEIDS.contains(serviceID.trim())) {
                return paramError();
            }
            if(StringUtil.isEmpty(compCode)){
                return errorMsg("compCode不能为空");
            }
            if(StringUtil.isEmpty(period)){
                return errorMsg("period不能为空");
            }
            if(StringUtil.isEmpty(userName)){
                return errorMsg("userName不能为空");
            }
            if(StringUtil.isEmpty(password)){
                return errorMsg("password不能为空");
            }

            //权限校验
            if(!StringUtil.isEmpty(compCode) && !StringUtil.isEmpty(userName) && !StringUtil.isEmpty(password)
                    && perUserName.equals(userName.trim()) && perPasswd.equals(password.trim())
                    || sysAppUserService.hasPermit("ALL", userName.trim(), password.trim())){
                perUserName = userName;
                perPasswd = password;
            }else{
                if ((!StringUtil.isEmpty(compCode) && !StringUtil.isEmpty(userName) && !StringUtil.isEmpty(password)
                        && perCompCode.equals(compCode.trim()) && perUserName.equals(userName.trim()) && perPasswd.equals(password.trim()))
                        || sysAppUserService.hasPermit(compCode.trim(), userName.trim(), password.trim())) {
                    perCompCode = compCode;
                    perUserName = userName;
                    perPasswd = password;
                } else {
                    return ServiceConstant.noPermission(ServiceConstant.SERVICE_FINANCE_DATA,ServiceConstant.PUBLISH_SERVICE);
                }
            }
            //配置compCode为ALL，即可查询任意数据
            if(compCode.equals("ALL")) compCode = null;
            //创建一个Map,封装查询条件
            Map<String,String> map = new HashMap<>();
            if(!StringUtil.isEmpty(compCode)) map.put("ORGNAZATIONCODE",compCode.trim());
            map.put("PERIOD",period.trim());
            if(!StringUtil.isEmpty(formId)) map.put("FORMID",formId.trim());
            if(!StringUtil.isEmpty(accountId)) map.put("ACCOUNTID",accountId.trim());
            if(!StringUtil.isEmpty(valueType)) map.put("valueType",valueType);
            serviceID = serviceID.trim();
            long pageNoInt;
            long pageSizeInt;
            //分页查询
            try {
                pageNoInt = PageUtil.handlePageNo(pageNo.trim());
                pageSizeInt = PageUtil.handlePageSize(pageSize.trim());
            }catch (Exception e){
                log.error("getLnAppData():err-page或者pagesize参数错误");
                return errorRequest();
            }
            if (serviceID.equals("LNFIN")) {
                return getLnFinDataByPage(map,pageNoInt,pageSizeInt,formName,accountName);
            } else {
                return getLnPlnDataByPage(map,pageNoInt,pageSizeInt,formName,accountName);
            }
        }catch (Exception e){
            log.error("getLnAppData():error-{}",e.getMessage());
            return errorMsg(e.getMessage());
        }
    }

    public String getLnFinDataByPage(Map<String,String> map,long pageNo, long pageSize,String formName,String accountName){
        return mdsLnfinDataService.getLnFinDataByPage(map,pageNo,pageSize,formName,accountName);
    }

    public String getLnPlnDataByPage(Map<String,String> map,long pageNo, long pageSize,String formName,String accountName){
        return mdsLnplnDataService.getLnFinDataByPage(map,pageNo,pageSize,formName,accountName);
    }

    /**
     * serviceID参数错误
     *
     * @return
     */
    private static String paramError() {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><service><name>ERP财务报表信息</name><type>发布服务</type><datalist><!--非法serviceID--></datalist></service>";
    }

    /**
     * 返回查询出错信息
     *
     * @param msg
     * @return
     */
    private String errorMsg(String msg) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><service><type>发布服务</type><datalist><!--error Message:" + msg + "--></datalist></service>";
    }
    /**
     * 返回错误信息
     *
     * @param result 错误结果
     * @param msg    错误信息详情
     * @return
     */
    private static String errorMsg(String result, String msg) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><service>" +
                "<result>" + result +
                "</result><msg>" + msg +
                "</msg></service>";
    }

    private static String errorRequest() {
        return errorMsg("-1", "请求参数不可识别，请检查！");
    }

}
